package com.sboot.shiro.common.config;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.Filter;

import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.sboot.shiro.common.shiro.AuthRealm;
import com.sboot.shiro.common.shiro.ResourceAccessFilter;

@Configuration
public class ShiroConfiguration {

	@Bean
	public ShiroFilterFactoryBean shiroFilter() {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
		Map<String, Filter> filters = new HashMap<>();
		filters.put("resourceAccessFilter", resourceAccessFilter());
		shiroFilterFactoryBean.setFilters(filters);
		
		filterChainDefinitionMap.put("login.jsp", "anon");
		filterChainDefinitionMap.put("/login", "anon");
		filterChainDefinitionMap.put("/doLogin", "anon");
		filterChainDefinitionMap.put("/logout", "anon");
		filterChainDefinitionMap.put("/static/**", "anon");
		filterChainDefinitionMap.put("/**", "authc");
		filterChainDefinitionMap.put("/biz/**", "resourceAccessFilter");
		
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
		shiroFilterFactoryBean.setLoginUrl("/login");
		shiroFilterFactoryBean.setSuccessUrl("/index");
		shiroFilterFactoryBean.setUnauthorizedUrl("/403");
		shiroFilterFactoryBean.setSecurityManager(securityManager());
		return shiroFilterFactoryBean;
	}

	@Bean
	public SecurityManager securityManager() {
		DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
		manager.setRealm(authRealm());
		return manager;
	}

	@Bean
	public AuthRealm authRealm() {
		AuthRealm authRealm = new AuthRealm();
		authRealm.setCredentialsMatcher(credentialsMatcher());
		return authRealm;
	}

	@Bean
	public CredentialsMatcher credentialsMatcher() {
		return new com.sboot.shiro.common.shiro.CredentialsMatcher();
	}
	
	@Bean
	public ResourceAccessFilter resourceAccessFilter() {
		ResourceAccessFilter raf = new ResourceAccessFilter();
		
		return raf;
	}
}
